<template>
  <div class="app-container">
<!--    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">-->
<!--      <el-form-item label="公司名称" prop="companyName">-->
<!--        <el-input-->
<!--            v-model="queryParams.companyName"-->
<!--            placeholder="请输入公司名称"-->
<!--            clearable-->
<!--            style="width: 200px"-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="公司状态" clearable style="width: 200px">-->
<!--          <el-option-->
<!--              v-for="dict in sys_normal_disable"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item>-->
<!--        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>-->
<!--        <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
<!--      </el-form-item>-->
<!--    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['setting:company:save']"
        >新增</el-button>
        <el-button icon="Search" type="primary" @click="getList">查询</el-button>
      </el-col>

    </el-row>

    <vxe-table
        v-if="refreshTable"
        border="inner"
        ref="tableRef"
        :tree-config="{transform: true, rowField: 'companyId', parentField: 'parentId' }"
        :data="deptList"
         >
      <vxe-column width="80"   tree-node ></vxe-column>
      <vxe-column field="companyName" title="公司名称" ></vxe-column>
      <vxe-column field="sortNum" title="排序"></vxe-column>
      <vxe-column field="status" title="状态">
        <template #default="{row}">
          {{ returnDictLabel(sys_normal_disable, row.status) }}
        </template>
      </vxe-column>
      <vxe-column field="status" title="创建时间">
        <template #default="{row}">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </vxe-column>
      <vxe-column fixed="right"  width="200" title="操作">
        <template #default="{row}">
          <el-button type="text" v-if="row.warehouseId" @click="handleUpdateWare(row)"  v-hasPermi="['setting:company:save']">修改</el-button>
          <el-button type="text" v-if="!row.warehouseId" @click="handleUpdate(row)"  v-hasPermi="['setting:company:save']">修改</el-button>
          <el-button type="text" v-if="!row.warehouseId"  style="color:green"  @click="handleAddWare(row)"  v-hasPermi="['setting:company:save']" >新增 </el-button >
          <el-button  type="text" style="color:red"  @click="handleDelete(row)"  v-hasPermi="['setting:company:delete']" >删除  </el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 添加或修改公司对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司状态">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加或修改仓库对话框 -->
    <el-dialog :title="titleWarehouse" v-model="openWarehouse" width="600px" append-to-body>
      <el-form ref="wareRef" :model="formWarehouse" :rules="rulesWarehouse" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库编码" prop="warehouseCode">
              <el-input v-model="formWarehouse.warehouseCode" @input="formWarehouse.warehouseCode=limitCharAndNumber(formWarehouse.warehouseCode)"  placeholder="仓库编码" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="formWarehouse.warehouseName"  placeholder="仓库名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货人" prop="receiptByName">
              <el-input v-model="formWarehouse.receiptByName"  placeholder="收货人" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="receiptPhone">
              <el-input v-model="formWarehouse.receiptPhone" @input="formWarehouse.receiptPhone=limitIntNumber(formWarehouse.receiptPhone)" :maxlength="11"  placeholder="联系方式" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货地址" prop="receiptAddress">
              <el-input v-model="formWarehouse.receiptAddress" placeholder="收货地址" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="formWarehouse.remark"  placeholder="备注" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="formWarehouse.status">
                <el-radio
                    v-for="dict in sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormWarehouse">确 定</el-button>
          <el-button @click="cancelWare">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  saveDept,
  saveWarehouse
} from "@/api/system/dept";
import {getCurrentInstance} from "vue";
import {flattenData} from "@/utils/shuangcheng";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const deptList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const deptOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    companyName: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: "上级公司不能为空", trigger: "blur" }],
    companyName: [{ required: true, message: "公司名称不能为空", trigger: "blur" }],
    sortNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询公司列表 */
function getList() {
  loading.value = true;
  listDept(queryParams.value).then(res => {
    deptList.value = flattenData(res.data)
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    warehouseId: undefined,
    parentId: undefined,
    companyName: undefined,
    sortNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: "0"
  };
  proxy.resetForm("deptRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
/** 新增按钮操作 */
function handleAdd() {
  reset();

  open.value = true;
  title.value = "添加公司";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();

  form.value =JSON.parse(JSON.stringify(row))
  open.value = true;
  title.value = "修改公司";
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      saveDept(form.value).then(response => {
        proxy.$modal.msgSuccess("保存成功");
        open.value = false;
        getList();
      });
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.companyName + '"的数据项?').then(function() {
    if(row.parentId>0){
      return delDept({'detailIds':[row.warehouseId]});
    }else{
      return delDept({'ids':[row.companyId]});
    }
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();

//仓库
let openWarehouse =ref(false)
let titleWarehouse =ref("")
let formWarehouse=ref({})
let  rulesWarehouse =ref({
  warehouseCode: [{required: true, message: "仓库编码不能为空", trigger: "blur"}],
  warehouseName: [{required: true, message: "仓库名称不能为空", trigger: "blur"}],
  receiptByName: [
    {required: true, message: "收货人不能为空", trigger: "blur"}
  ],
  receiptPhone: [
    {required: true, message: "联系方式不能为空", trigger: "blur"},
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    }
  ],
  receiptAddress: [{required: true, message: "收货地址不能为空", trigger: "blur"}],
})

function submitFormWarehouse() {
  proxy.$refs["wareRef"].validate(valid => {
    if (valid) {
      saveWarehouse(formWarehouse.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        openWarehouse.value = false;
        getList();
      });
    }
  });
}
function cancelWare() {
  openWarehouse.value = false;
  formWarehouse.value={}
}

//新增仓库
function handleAddWare(row){
  formWarehouse.value.parentId=row.companyId
  openWarehouse.value = true;
  titleWarehouse.value='新建仓库'
}

function handleUpdateWare(row){
  formWarehouse.value =JSON.parse(JSON.stringify(row))
  console.log(formWarehouse.value)
  openWarehouse.value = true;
  titleWarehouse.value='修改仓库'
}

</script>
